package com.zjitc.utils.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/26 15:48
 * @description:
 */
public class RabbitMq implements RabbitMessage {

    Connection connection;
    String queueName;

    public RabbitMq() {
        ConnectionFactory factory = new ConnectionFactory();
        queueName = "getMail";
        factory.setHost("47.96.75.158");
        factory.setUsername("lhl");
        factory.setPassword("lhl");
        factory.setVirtualHost("lhl");
        try {
            this.connection = factory.newConnection();

            Channel channel = this.connection.createChannel();
            channel.queueDeclare(queueName, true, false, false, null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int sendMessage(String message) {
        Channel channel = null;
        try {
            channel = this.connection.createChannel();
            channel.basicPublish("", queueName, null, message.getBytes("UTF-8"));

            System.out.println(message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        }
        if (message != null) {
            return 1;
        } else {
            return -1;
        }
    }

    public void close() {
        if (this.connection != null) {
            try {
                this.connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
